<script setup lang="ts">

import CodeBase from "~/components/common/CodeBase.vue";
import {Super_POST} from "~/utils/httpUtils";
import {usePaymentUtilsGenerateOrderNo} from "~/utils/paymentUtils";
import io, {Socket} from 'socket.io-client'
import EmptyBase from "~/components/common/EmptyBase.vue";
import Wechat from "~/components/icons/wechat.vue";
import {useAuthupdateUserInfo} from "~/composables/authhooks";
const code_text = ref("");//code支付二维码练级
const socketid = ref('')
const {user}=storeToRefs(useAuthStore())

interface Props {
  amount: number;
  description?: string; //商品描述
  onPaySuccess?: () => void;
  onPayFail?: () => void;
  onPayCancel?: () => void;
}

const props = withDefaults(defineProps<Props>(), {
  amount: 0,
  description: 'AI服务',
  onPaySuccess: () => {
  },
  onPayFail: () => {
  },
  onPayCancel: () => {
  }
})
// 监听金额变化，刷新二维码
watch(props, async (newValue) => {
  console.log('金额变化',newValue)
  code_text.value = ''
  code_text.value = await handelGetCode()
},{
  deep:true
})


//支付结果
const payResult = ref(false);

interface PayOrder {
  user_id: string; //user_id,用户id
  out_trade_no: string; //订单号
  description: string;
  amount: Amount; //金额
  order_status: 0 | 1 | 2; //0:未支付 1:已支付 2:已退款;
  order_create_time: number;
  order_pay_time: number;
  transaction_id: string;
  trade_type: string;
  payer: Payer;
}

interface Amount {
  total: number;
  payer_total?: number;
}

interface Payer {
  openid: string;
  socketid: string;
}
//通过socket.io 监听支付结果
const {isCommercial}=useAppStore()
const socket = io(isCommercial?useRuntimeConfig().public.paySocket:useGlobalConfig.Pay.payUrl.replace('/api','') as string)
socket.on('connect', async () => {
  socketid.value = socket.id + ''
  code_text.value = await handelGetCode();
  user.value.socket_id= socket.id + ''
  console.log('connect', socket.id)
})
socket.on('message', async (msg) => {
  const data = JSON.parse(msg)
  if (data.type === 'pay_success') {
   await handelQueryPayResult()
  }
  console.log('message',msg)
})
// socket.on('pay_result', (data: PayOrder) => {
//   if (data.out_trade_no === out_trade_no.value) {
//     payResult.value = true;
//   }
// })


onMounted(async () => {

})

//生成订单号码
const out_trade_no = ref('')

const handelGetCode = async (): Promise<string> => {
  //生成订单
  out_trade_no.value = usePaymentUtilsGenerateOrderNo();
  console.log('socketid',socketid.value)
  return await Super_POST('/pay/order', {
    user_id: useAuthStore().user?._id,
    out_trade_no:out_trade_no.value,
    description: props.description,
    amount: {
      total: props.amount
    },
    payer: {
      socketid: socketid.value
    }
  }as PayOrder) as string;
}

/**
 * 查询支付结果
 */
const handelQueryPayResult = async () => {
  const order = await Super_POST('/pay/query', {
    out_trade_no: out_trade_no.value,
  }) as PayOrder;
  if (order.order_status === 1) {
    payResult.value = true;
    // 支付成功，更新本地账户的余额信息
    await useAuthupdateUserInfo()
  }else {
    useSnackbarStore().showWarningMessage('未查询到支付信息！')
  }
}


// setInterval(() => {
//   handelQueryPayResult();
// }, 1000)


</script>

<template>
<!--  <v-btn @click="submit_test_task">提交绘画任务</v-btn>-->

  <v-sheet class="d-flex flex-column align-center justify-center">
    <wechat/><span>微信支付</span>

    <empty-base v-if="!code_text"/>
    <h2 v-else>请使用微信扫码支付</h2>
    <code-base v-else :text="code_text"/>
    <v-label class="my-4">订单金额：{{props.amount/100}}元</v-label>
    <!--  支付成功-->
    <div v-if="payResult" class="d-flex flex-row align-center justify-center">
      <v-icon icon="mdi-check-circle-outline" color="success"/>
      <h2>支付成功</h2>
    </div>
    <div v-else class="d-flex flex-column align-center justify-center">
      <span>支付后页面无响应，可点击下方按钮手动查询支付结果</span>
      <v-btn class="mt-5" color="warning" size="small" variant="flat" @click="handelQueryPayResult">查询</v-btn>
    </div>
  </v-sheet>


</template>

<style scoped lang="scss">

</style>